from flask import Flask, request, jsonify
from flask_cors import CORS
import sqlite3
import json

app = Flask(__name__)
CORS(app)  # 允许跨域请求

# 配置Flask应用以确保正确处理中文字符编码
app.config['JSON_AS_ASCII'] = False  # 确保JSON响应中的非ASCII字符(如中文)正确显示

# 数据验证中间件
def validate_user_data(data, is_update=False):
    # 验证必需字段
    required_fields = ['user_type', 'username', 'status']
    if not is_update:
        required_fields.append('password')  # 创建用户时密码是必需的
    
    for field in required_fields:
        if field not in data:
            return {'error': f'缺少必需字段: {field}'}, False
    
    # 验证用户类型
    # 移除严格的用户类型验证，允许所有用户类型值
    # valid_user_types = ['管理员', '普通用户']
    # if 'user_type' in data and data['user_type'] not in valid_user_types:
    #     return {'error': f'无效的用户类型，必须是: {"或".join(valid_user_types)}'}, False
    
    # 验证用户名不为空
    if 'username' in data and not data['username'].strip():
        return {'error': '用户名不能为空'}, False
    
    # 验证密码不为空且长度合理 - 只在创建用户或明确提供密码时验证
    if 'password' in data and data['password'] is not None:
        # 编辑用户时，如果密码字段为空字符串，表示不想修改密码，应该跳过验证
        if not is_update or (data['password'] != ''):
            if not data['password'].strip():
                return {'error': '密码不能为空'}, False
            if len(data['password']) < 6:
                return {'error': '密码长度不能少于6个字符'}, False
    
    # 验证状态
    valid_statuses = ['激活', '未激活', '已禁用']
    if 'status' in data and data['status'] not in valid_statuses:
        return {'error': f'无效的状态，必须是: {"或".join(valid_statuses)}'}, False
    
    return None, True

# 数据库连接函数
def get_db_connection():
    db_path = r'd:\manage1\graduation-project\manage1\manage1\manage\db.sqlite3'
    conn = sqlite3.connect(db_path)
    conn.row_factory = sqlite3.Row  # 允许使用字典方式访问结果
    return conn

# 修改jsonify响应函数，确保响应头包含正确的字符编码
def custom_jsonify(*args, **kwargs):
    response = jsonify(*args, **kwargs)
    response.headers['Content-Type'] = 'application/json; charset=utf-8'
    return response

# 获取所有用户
@app.route('/api/users', methods=['GET'])
def get_users():
    conn = get_db_connection()
    cursor = conn.cursor()
    
    # 获取查询参数
    username = request.args.get('username', '')
    user_type = request.args.get('user_type', '')
    
    # 构建查询
    query = 'SELECT id, user_type, username, status FROM property_user WHERE 1=1'
    params = []
    
    if username:
        query += ' AND username LIKE ?'
        params.append(f'%{username}%')
    
    if user_type:
        query += ' AND user_type = ?'
        params.append(user_type)
    
    cursor.execute(query, params)
    users = [dict(row) for row in cursor.fetchall()]
    
    conn.close()
    response = jsonify(users)
    response.headers['Content-Type'] = 'application/json; charset=utf-8'
    return response

# 更新create_user函数确保正确处理中文
@app.route('/api/users', methods=['POST'])
def create_user():
    data = request.get_json()
    
    # 使用验证中间件
    error, is_valid = validate_user_data(data)
    if not is_valid:
        response = jsonify(error)
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response, 400
    
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        
        # 检查用户名是否已存在
        cursor.execute('SELECT id FROM property_user WHERE username = ?', (data['username'],))
        if cursor.fetchone():
            conn.close()
            response = jsonify({'error': '用户名已存在'})
            response.headers['Content-Type'] = 'application/json; charset=utf-8'
            return response, 400
        
        # 插入新用户
        cursor.execute(
            'INSERT INTO property_user (user_type, username, password, status) VALUES (?, ?, ?, ?)',
            (data['user_type'], data['username'], data['password'], data['status'])
        )
        
        user_id = cursor.lastrowid
        conn.commit()
        conn.close()
        
        # 返回创建的用户信息
        response = jsonify({
            'id': user_id,
            'user_type': data['user_type'],
            'username': data['username'],
            'status': data['status']
        })
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response, 201
    
    except Exception as e:
        response = jsonify({'error': str(e)})
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response, 500

# 获取单个用户
@app.route('/api/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute('SELECT id, user_type, username, status FROM property_user WHERE id = ?', (user_id,))
    
    user = cursor.fetchone()
    conn.close()
    
    if user:
        response = jsonify(dict(user))
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response
    else:
        response = jsonify({'error': 'User not found'})
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response, 404

# 更新用户
@app.route('/api/users/<int:user_id>', methods=['PUT'])
def update_user(user_id):
    data = request.get_json()
    
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        
        # 检查用户是否存在
        cursor.execute('SELECT id FROM property_user WHERE id = ?', (user_id,))
        if not cursor.fetchone():
            conn.close()
            response = jsonify({'error': '用户不存在'})
            response.headers['Content-Type'] = 'application/json; charset=utf-8'
            return response, 404
        
        # 验证数据格式 - 明确指出这是更新操作
        error, is_valid = validate_user_data(data, is_update=True)
        if not is_valid:
            conn.close()
            response = jsonify(error)
            response.headers['Content-Type'] = 'application/json; charset=utf-8'
            return response, 400
        
        # 构建更新语句
        update_fields = []
        params = []
        
        if 'user_type' in data:
            update_fields.append('user_type = ?')
            params.append(data['user_type'])
        if 'username' in data:
            update_fields.append('username = ?')
            params.append(data['username'])
        # 只在密码字段存在且非空字符串时才更新密码
        if 'password' in data and data['password'] and data['password'].strip():
            update_fields.append('password = ?')
            params.append(data['password'])
        if 'status' in data:
            update_fields.append('status = ?')
            params.append(data['status'])
        
        if update_fields:
            params.append(user_id)
            query = 'UPDATE property_user SET ' + ', '.join(update_fields) + ' WHERE id = ?'
            cursor.execute(query, params)
            conn.commit()
        
        # 返回更新后的用户信息
        cursor.execute('SELECT id, user_type, username, status FROM property_user WHERE id = ?', (user_id,))
        user = dict(cursor.fetchone())
        
        conn.close()
        response = jsonify(user)
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response
    
    except Exception as e:
        response = jsonify({'error': str(e)})
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response, 500

# 删除用户
@app.route('/api/users/<int:user_id>', methods=['DELETE'])
def delete_user(user_id):
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        
        # 检查用户是否存在
        cursor.execute('SELECT id FROM property_user WHERE id = ?', (user_id,))
        if not cursor.fetchone():
            conn.close()
            response = jsonify({'error': 'User not found'})
            response.headers['Content-Type'] = 'application/json; charset=utf-8'
            return response, 404
        
        # 删除用户
        cursor.execute('DELETE FROM property_user WHERE id = ?', (user_id,))
        conn.commit()
        conn.close()
        
        response = jsonify({'message': 'User deleted successfully'})
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response
    
    except Exception as e:
        response = jsonify({'error': str(e)})
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response, 500

if __name__ == '__main__':
    app.run(debug=True, port=5000)
